import { Component, Input, OnInit, Inject, forwardRef } from '@angular/core';

import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { ComItem } from '../../route/entry/com-item';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';

@Component({
  selector: 'app-fixed-tab',
  templateUrl: './fixed-tab.component.html',
  styleUrls: ['./fixed-tab.component.scss'],
})
// tslint:disable
export class FixedTabComponent implements OnInit {
  subComs: ComItem[] = [];
  isNav1 = false;
  isNav2 = false;
  isTab1 = false;
  isTab2 = false;
  isTab3 = false;
  isTab4 = false;
  isTab5 = false;
  @Input() tagData: any;
  aWidth: string;
  appTypeCustom: any;
  constructor(
    private eventService: EventService,
    private httpService: HttpService,
    private appGlobalService: AppGlobalService) {
    if (this.eventService.eventEmit.listenerCount('refreshSubTab') > 0) {
      this.eventService.eventEmit.removeListener('refreshSubTab');
    }
    this.eventService.eventEmit.on('refreshSubTab', data => {
      console.log('refreshSubTab------->sub');
      if (this.tagData.currentTab) {
        const tmp = document.getElementById("fixedNavTab" + this.tagData.currentTab);
        if (tmp) {
          tmp.click();
        }
      }
    });
    if (this.eventService.eventEmit.listenerCount('refreshFixedTabForMsg') > 0) {
      this.eventService.eventEmit.removeListener('refreshFixedTabForMsg');
    }
    this.eventService.eventEmit.on('refreshFixedTabForMsg', data => {
      if (localStorage.getItem('refreshFixedTabForMsgTag')) {
        localStorage.setItem('refreshFooterComs', 'false');
        localStorage.removeItem('refreshFixedTabForMsgTag');
        // const tmp = document.getElementById("fixedNavTab" + data);
        // setTimeout(() => {
        //   if (tmp) { tmp.click(); }
        // }, 150);
        // 导致的bug ：[步骤]
        // 1、进入我的发布，从转让tab页选择一条转让信息点击进入详情中
        // 2、下拉至在线聊天，点击进入聊天页面
        // 3、点击聊天界面返回，详情页面返回，返回到了我的发布中的选址tab页
        // [结果]
        // 返回到了选址tab页
        // 修改为：
        if (this.tagData.currentTab) {
          const tmp = document.getElementById("fixedNavTab" + this.tagData.currentTab);
          if (tmp) {
            tmp.click();
          }
        }
      }
    });

    // todo 注释用于刷新消息列表
    // if (this.eventService.eventEmit.listenerCount('refreshFixedTabInvationMsg') > 0) {
    //   this.eventService.eventEmit.removeListener('refreshFixedTabInvationMsg');
    // }
    // // 用于更新消息之后刷新
    // this.eventService.eventEmit.on('refreshFixedTabInvationMsg', data => {
    //   if (localStorage.getItem('refreshFixedTabInvationMsgTag')) {
    //     localStorage.setItem('refreshFooterComs', 'false');
    //     localStorage.removeItem('refreshFixedTabInvationMsgTag');
    //     //
    //     if (data) {
    //       const tmp = document.getElementById("fixedNavTab" + data);
    //       // 不刷新 innerText存在undefined 情况
    //       if (tmp && tmp.innerText && (tmp.innerText === '转让' || tmp.innerText === '选址')) {
    //       } else {
    //         if (tmp) {
    //           tmp.className = 'active'; // 点击之后样式激活
    //           tmp.click();
    //         }
    //       }
    //     }
    //   }
    // });
    if (this.eventService.eventEmit.listenerCount('refreshFixedSpanInvationMsg') > 0) {
      this.eventService.eventEmit.removeListener('refreshFixedSpanInvationMsg');
    }
    // 用于更新消息之后刷新
    this.eventService.eventEmit.on('refreshFixedSpanInvationMsg', data => {
      if (localStorage.getItem('refreshFixedSpanInvationMsgTag')) {
        localStorage.setItem('refreshFooterComs', 'false');
        localStorage.removeItem('refreshFixedTabInvationMsgTag');
        if (data > 0) {
          const tmp = document.getElementById("fixedNavTab" + data);
          if (tmp) { tmp.click(); }
        }
      }
    });
  }

  ngOnInit() {


    // 

    // 需要判断当前是在tab1~tab5 还是nav add by andrew.wen
    const ionRouterOutlet = document.getElementsByTagName('ion-router-outlet');
    if (ionRouterOutlet && ionRouterOutlet[0]) {
      try {
        const tabTtmlCollection = ionRouterOutlet[0];
        const len = tabTtmlCollection.children.length;
        for (let i = len - 1; i > 0; i--) {
          const tempTabObj = tabTtmlCollection.children[i];
          if (!tempTabObj.classList.contains('ion-page-hidden')) { // 没有隐藏的tab
            if (tempTabObj.classList.contains('can-go-back')) {
              if (tempTabObj.localName !== 'app-search-history') {
                if (document.getElementsByTagName('app-footer-coms') && document.getElementsByTagName('app-footer-coms').length > 0 && localStorage.getItem('currAction')) {
                  localStorage.removeItem('currAction');
                  return;
                }
              } else {
                setTimeout(() => {
                  // if (this.appTypeCustom !== 'LJ') {
                  localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.tagData));
                  this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
                  // }
                }, 200);
              }
              break;
            }
          }
        }
      } catch (e) {
        console.log('msg----->,' + JSON.stringify(e));
      }
    }
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    if (this.tagData.data[0].label === '转让') {
      this.initAll();
      this.isNav1 = true;
      setTimeout(() => {
        // if (this.appTypeCustom !== 'LJ') {
        localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.tagData));
        this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
        // }
      }, 200);
      return;
    }


    if (ionRouterOutlet && ionRouterOutlet[0]) {
      try {
        const tabTtmlCollection = ionRouterOutlet[0];
        const len = tabTtmlCollection.children.length;
        for (let i = 0; i < len; i++) {
          const tempTabObj = tabTtmlCollection.children[i];
          if (!tempTabObj.classList.contains('ion-page-hidden')) { // 没有隐藏的tab
            const nodeName = String(tabTtmlCollection.children[i].nodeName); // TAB3
            this.initAll();
            if (tempTabObj.classList.contains('can-go-back')) {
              if (nodeName.indexOf('NAV') > -1) {
                this.isNav1 = true;
              }
              break;
            } else {
              const tabTtmlCollectionChildrenLen = tabTtmlCollection.children.length;
              if (tabTtmlCollectionChildrenLen >= 2) {
                if (!tempTabObj.classList.contains('ion-page-hidden') && tabTtmlCollection.children[tabTtmlCollectionChildrenLen - 1].classList.contains('can-go-back')) {
                  this.isNav1 = true;
                  break;
                }
              }
              if (tempTabObj.children.length >= 2) {
                if (nodeName.indexOf('TAB3') > -1) {
                  this.isTab3 = true;
                  // localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.tagData));
                  // this.eventService.eventEmit.emit('refreshTab3FixedContainer', 'refreshTab3FixedContainer');
                  // 判断是否有红点
                  if (this.appGlobalService.invitationMsgBdge) {
                    const tmp = (tempTabObj.children[0].children[1].children[0].children[1]) as HTMLElement;
                    tmp.className = 'spanBadge';
                  }
                  break;
                } else if (nodeName.indexOf('TAB1') > -1) {
                  this.isTab1 = true;
                  break;
                } else if (nodeName.indexOf('TAB2') > -1) {
                  this.isTab2 = true;
                  break;
                } else if (nodeName.indexOf('TAB4') > -1) {
                  this.isTab4 = true;
                  break;
                } else if (nodeName.indexOf('TAB5') > -1) {
                  this.isTab5 = true;
                  break;
                }
              } else {

                continue;
              }
            }
          }
        }
      } catch (e) {
        console.log('msg----->,' + JSON.stringify(e));
      }
    }
    if (!this.isNav1 && !this.isNav2 && !this.isTab1 && !this.isTab2 && !this.isTab3 && !this.isTab4 && !this.isTab5 && (localStorage.getItem('currentPath') === 'nav1' || localStorage.getItem('currentPath') === 'nav2')) {
      this.isNav1 = true;
    }
    if (!this.appGlobalService.lastMessageIndex || this.tagData.currentTab === this.appGlobalService.lastMessageIndex) {
      this.currentData();
    } else {
      setTimeout(() => {
        // 邀约 系统 都有新的 系统消息优先
        // 只有一个有新消息 则优先新消息
        // 都没有在再按配置 如更非第一次加载消息模块 则记住上一次的选中的
        // 原始配置的 选中项
        const orgTab = this.tagData.currentTab;
        // 先看是不是消息
        if (this.tagData.data[0].label === '系统消息') {
          // localStorage.setItem('needRefreshTab3', 'true');
          // 系统消息数
          const sysNum = Number(this.tagData.data[0].badge);
          // 邀约 系统 都有新的 系统消息优先
          if (Number(localStorage.getItem('inMsgNum')) > 0 && sysNum > 0) {
            this.tagData.currentTab = '0';
          } else if (Number(localStorage.getItem('inMsgNum')) > 0) {
            this.tagData.currentTab = '1';
          } else if (sysNum > 0) {
            this.tagData.currentTab = '0';
          } else {
            // 都没有在再按配置 如更非第一次加载消息模块 则记住上一次的选中的
            if (this.appGlobalService.lastMessageIndex) {
              this.tagData.currentTab = this.appGlobalService.lastMessageIndex;
            }
          }
          // 最终确定与原始配置不一致实时 刷新页面
          if (orgTab !== this.tagData.currentTab) {
            this.reloadCurrentTab(true);
          } else {
            // 默认配置页面
            this.currentData();
          }
        } else {
          // 默认配置页面
          this.currentData();
        }
      }, 50);
    }
  }

  async currentData() {
    const homeTopCssType2Segment = document.getElementById('homeTopCssType2Segment');
    if (homeTopCssType2Segment) {
      // this.eventService.eventEmit.emit("refreshNav1FixedContainer", "refreshNav1FixedContainer");
      localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.tagData));
      this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
      return;
    }

    // 需要判断当前是在tab1~tab5 还是nav add by andrew.wen
    const ionRouterOutlet = document.getElementsByTagName('ion-router-outlet');
    if (ionRouterOutlet && ionRouterOutlet[0]) {
      try {
        const tabTtmlCollection = ionRouterOutlet[0];
        const len = tabTtmlCollection.children.length;
        for (let i = len - 1; i > 0; i--) {
          const tempTabObj = tabTtmlCollection.children[i];
          if (!tempTabObj.classList.contains('ion-page-hidden')) { // 没有隐藏的tab
            if (tempTabObj.classList.contains('can-go-back')) {
              if (tempTabObj.children[0] && tempTabObj.children[0].children[1]) {
                const tmp = (tempTabObj.children[0].children[1].children[0].children[this.tagData.currentTab]) as HTMLElement;
                if (tmp !== undefined) {
                  if(tmp.classList.contains('needClick')){
                     tmp.click();
                  }else{
                    window['appGlobalService'].loadFixedTabCallBack(1);
                  }
                   
                  // 2024.10.10 已禁用该click 使用 如下方式唤醒 begin
                  // localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.subTagData));
                  // this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
                  // 2024.10.10 已禁用该click 使用 如下方式唤醒 end
                  // 2024.10.24 调用回调
                 
                }
              }
              break;
            } else {
              if (tempTabObj.children.length >= 2) {
                if (tempTabObj.children[0] && tempTabObj.children[0].children[1]) {
                  const tmp = (tempTabObj.children[0].children[1].children[0].children[0]) as HTMLElement;
                  if (tmp !== undefined) {
                    if(tmp.classList.contains('needClick')){
                      tmp.click();
                   }else{
                      window['appGlobalService'].loadFixedTabCallBack(1);
                   }
                  // 2024.10.10 已禁用该click 使用 如下方式唤醒 begin
                  // localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.subTagData));
                  // this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
                  // 2024.10.10 已禁用该click 使用 如下方式唤醒 end
                  }
                }
                break;
              } else {
                continue;
              }
            }
          }
        }
      } catch (e) {
        console.log('msg----->,' + JSON.stringify(e));
      }
    }
  }

  // 做了延时150 用于内部容器清除components组件
  reloadCurrentTabByClick() {
    if (this.tagData.currentTab) {
      const tmp = document.getElementById("fixedNavTab" + this.tagData.currentTab);
      setTimeout(() => {
        if (tmp) { tmp.click(); }
      }, 150);
    }
  }

  reloadCurrentTab(isNeedClick?) {
    if (isNeedClick) {
      this.reloadCurrentTabByClick();
    }
  }

  initAll() {
    this.isNav1 = false;
    this.isNav2 = false;
    this.isTab1 = false;
    this.isTab2 = false;
    this.isTab3 = false;
    this.isTab4 = false;
    this.isTab5 = false;
  }
}
